export function deepcopy(data) {
  try {
    return JSON.parse(JSON.stringify(data));
  } catch (error) {
    console.error(error);
    return {};
  }
}
//path为key 的对象数组扁平化
export function flattenPaths(obj, path = [], result = {}) {
  if (typeof obj === "object" && obj !== null) {
    if (Array.isArray(obj)) {
      obj.forEach((item, index) => flattenPaths(item, path.concat(index), result));
    } else {
      Object.keys(obj).forEach(key => flattenPaths(obj[key], path.concat(key), result));
    }
  } else {
    result[path.join(".")] = obj;
  }
  return result;
}
//path查询
export function searchFlattenedPaths(flattenedObj, searchString) {
  const results = [];

  // 遍历扁平化对象的所有 key-value 对
  Object.keys(flattenedObj).forEach(key => {
    // 如果 key 包含搜索字符串，则添加该 key-value 对到结果中
    if (key.includes(searchString)) {
      results.push({ key, value: flattenedObj[key] });
    }
  });

  return results;
}

// 对象key筛选
export function filterNestedByKeys(data, keys) {
  const keyArray = keys.split(" ");
  function recursiveFilter(obj) {
    if (Array.isArray(obj)) {
      let result = obj.map(item => recursiveFilter(item)).filter(item => item !== undefined);
      return result.length > 0 ? result : undefined;
    } else if (typeof obj === "object" && obj !== null) {
      let result = {};
      let hasMatchedKey = false;

      keyArray.forEach(key => {
        if (obj.hasOwnProperty(key)) {
          result[key] = obj[key];
          hasMatchedKey = true;
        }
      });

      let hasNestedMatch = false;
      for (let k in obj) {
        let filteredChild = recursiveFilter(obj[k]);
        if (filteredChild !== undefined) {
          result[k] = filteredChild;
          hasNestedMatch = true;
        }
      }

      if (hasMatchedKey || hasNestedMatch) {
        return result;
      }
    }
    return undefined;
  }

  const filteredData = recursiveFilter(data);
  return Array.isArray(data) ? filteredData || [] : filteredData || {};
}

//path-obj还原 未验证
export function unflattenArrayPaths(flattenedObj) {
  const result = [];
  const pathKeys = Object.keys(flattenedObj);

  pathKeys.forEach(path => {
    const value = flattenedObj[path];
    const pathParts = path.split(".");
    let currentLevel = result;

    // 遍历路径的每一部分，除了最后一个
    for (let i = 0; i < pathParts.length - 1; i++) {
      const key = pathParts[i];
      const isIndex = !isNaN(key as any);

      // 如果是数组索引，确保当前层级是数组
      if (isIndex) {
        if (!Array.isArray(currentLevel)) {
          currentLevel = [currentLevel]; // 将当前对象包装为数组
        }
        // 获取或初始化对应索引的对象
        const index = parseInt(key, 10);
        if (!currentLevel[index]) {
          currentLevel[index] = {}; // 初始化数组中的对象
        }
        currentLevel = currentLevel[index];
      } else {
        // 如果是对象键，确保当前层级是对象
        if (typeof currentLevel !== "object" || currentLevel === null) {
          //@ts-expect-errors
          currentLevel = {}; // 初始化当前层级为对象
        }
        // 确保键对应的值是对象或数组，以便可以进一步嵌套
        if (!currentLevel[key] || typeof currentLevel[key] !== "object") {
          currentLevel[key] = {}; // 初始化键对应的值为对象
        }
        currentLevel = currentLevel[key];
      }
    }

    // 设置最后一个键的值
    const lastKey = pathParts[pathParts.length - 1];
    //@ts-expect-errors
    if (isNaN(lastKey)) {
      // 如果最后一个键不是索引，则将其设置为值
      currentLevel[lastKey] = value;
    } else {
      // 如果最后一个键是索引，且当前层级不是数组，则需要初始化数组
      const index = parseInt(lastKey, 10);
      if (!Array.isArray(currentLevel)) {
        currentLevel = Array(index + 1)
          .fill(null)
          .map(() => ({})); // 初始化足够长度的数组，每个元素都是空对象
      }
      currentLevel[index] = value; // 设置数组对应索引的值
    }
  });

  return result;
}

//按照path 模式筛选对象
export function getValueByPath(data, path) {
  const pathArray = path.split(".");

  function recursiveGetValue(obj, pathArr) {
    if (pathArr.length === 0) {
      return obj;
    }

    const [currentKey, ...restPath] = pathArr;

    if (Array.isArray(obj) && currentKey === "num") {
      return obj.map(item => recursiveGetValue(item, restPath)).filter(result => result !== undefined);
    } else if (obj && obj.hasOwnProperty(currentKey)) {
      return recursiveGetValue(obj[currentKey], restPath);
    }

    return undefined;
  }

  return recursiveGetValue(data, pathArray);
}
// 按照path筛选对象，支持a.b.c[1,2,3]进行数组筛选
// export function getValueByPathAndNum(data, path) {
//   const pathSegments = path.split(".");

//   return pathSegments.reduce((current, segment) => {
//     if (!current) return null;

//     const arrayMatch = segment.match(/(\w+)\[(.*?)\]/);
//     if (arrayMatch) {
//       const arrayName = arrayMatch[1];
//       const indices = arrayMatch[2].split(",").map(Number);

//       if (!Array.isArray(current[arrayName])) return null;

//       return indices.map(index => current[arrayName][index]);
//     } else {
//       return current[segment];
//     }
//   }, data);
// }
export function getValueByPathAndNum(data, path) {
  const pathSegments = path.split(".");

  return pathSegments.reduce((current, segment) => {
    if (!current) return null;

    // 检查是否为数组访问形式，例如 a[0,1]
    const arrayMatch = segment.match(/(\w+)\[(.*?)\]/);
    if (arrayMatch) {
      const arrayName = arrayMatch[1];
      const index = parseInt(arrayMatch[2], 10); // 改为解析单个索引

      if (!Array.isArray(current[arrayName]) || current[arrayName].length <= index) return null;

      return current[arrayName][index];
    } else {
      // 直接作为键访问
      return current[segment];
    }
  }, data);
}
export function mergePropValue(raw, target, maps = {}, spc = []) {
  for (const key in target) {
    if (spc.includes(key)) continue;
    if (maps[key]) {
      target[key] = raw[maps[key]];
    } else if (raw[key]) {
      target[key] = raw[key];
    }
  }
}
export function compressArray(arr) {
  return arr.reduce((acc, item) => {
    const { alias, raw } = item;
    if (alias) {
      acc[raw] = alias;
    }
    return acc;
  }, {});
}
